// homepage.cpp
#include "homepage.h"
#include "ui_homepage.h"
#include "globalval.h"
#include <QPainter>
#include <QPaintEvent>

HomePage::HomePage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HomePage),
    myCar(nullptr),
    tempCurve(nullptr),
    parkingSurveillance(nullptr),
    setWig(nullptr),
    search(nullptr),
    deviceOfflineLabel(nullptr)
{
    ui->setupUi(this);

    // 加载背景图片
    backgroundPixmap = QPixmap(BEIJING);

    // 设置窗口背景透明，以便自定义绘制
    setAttribute(Qt::WA_TranslucentBackground);

    // 设置堆栈窗体背景透明
    ui->stackedWidget->setStyleSheet("background: transparent;");

    // 设置左侧控件的背景透明或半透明
    ui->listWidget->setStyleSheet("background-color: rgba(255, 255, 255, 200);");
    ui->line_mqtt_address->setStyleSheet("background-color: rgba(255, 255, 255, 220);");
    ui->pushButton->setStyleSheet("background-color: rgba(255, 255, 255, 220);");

    // 实例化五个界面
    myCar = new My_Car;
    tempCurve = new Temperature_Curve;
    parkingSurveillance = new Parking_Surveillance;
    setWig = new SetWig;
    search = new Search;

    connect(setWig, &SetWig::modeChanged, this, &HomePage::onModeChanged);

    // 将界面添加到堆栈窗体
    ui->stackedWidget->addWidget(myCar);
    ui->stackedWidget->addWidget(tempCurve);
    ui->stackedWidget->addWidget(parkingSurveillance);
    ui->stackedWidget->addWidget(setWig);
    ui->stackedWidget->addWidget(search);

    // 连接列表界面和堆栈窗体的信号
    QObject::connect(ui->listWidget, SIGNAL(currentRowChanged(int)),
                     ui->stackedWidget, SLOT(setCurrentIndex(int)));

    // mqtt相关
    MqttHandler *mqtt = new MqttHandler;
    GlobalVal::mqtt = mqtt;
    mqtt->setHost(QHostAddress("127.0.0.1"));
    mqtt->setPort(1883);
    mqtt->connectToHost();

    // 连接MQTT信号到各个界面的槽函数
    QObject::connect(mqtt, &MqttHandler::dataUpSignal, tempCurve, &Temperature_Curve::dataUpSlot);
    QObject::connect(mqtt, &MqttHandler::dataUpSignal, myCar, &My_Car::dataUpSlot);
    QObject::connect(mqtt, &MqttHandler::dataUpSignal, parkingSurveillance, &Parking_Surveillance::dataUpSlot);
    QObject::connect(mqtt, &MqttHandler::dataUpSignal, search, &Search::dataUpSlot);  // 添加这行
    QObject::connect(mqtt, &MqttHandler::dataUpSignal, this, &HomePage::onDataReceived);

    // 连接设备离线信号到所有界面
    QObject::connect(mqtt, &MqttHandler::deviceOfflineSignal, this, &HomePage::onDeviceOffline);

    // 在连接成功的处理中更新所有界面状态
    QObject::connect(mqtt, &MqttHandler::connectedSignal, this, [this]() {
        qDebug() << "MQTT连接成功，更新所有界面状态";

        // 隐藏设备离线警告
        hideDeviceOfflineWarning();

        if (tempCurve) tempCurve->setConnectedState(true);
        if (myCar) myCar->setConnectedState(true);
        if (parkingSurveillance) parkingSurveillance->setConnectedState(true);
        if (setWig) setWig->setMqttConnected(true);
        if (search) search->setConnectedState(true);  // 添加这行

        // 立即发送刷新请求（code3）
        qDebug() << "MQTT连接成功，立即发送刷新请求";
        sendRefreshRequest();

        // 同时发送模式选择请求，确保设备知道当前模式
        sendModeRequest(1);
    });

    // 初始化设备离线标签
    setupDeviceOfflineLabel();
}

// 初始化设备离线标签
void HomePage::setupDeviceOfflineLabel()
{
    deviceOfflineLabel = new QLabel(this);
    deviceOfflineLabel->setText("设备离线");
    deviceOfflineLabel->setAlignment(Qt::AlignCenter);
    deviceOfflineLabel->setStyleSheet("color: red; font-size: 50px; font-weight: bold; background-color: rgba(255, 255, 0, 200); border: 3px solid red; padding: 20px;");
    deviceOfflineLabel->setGeometry(this->width()/2 - 200, 50, 400, 80);
    deviceOfflineLabel->setVisible(false);
    deviceOfflineLabel->raise(); // 确保在最上层
}

// 显示设备离线警告
void HomePage::showDeviceOfflineWarning()
{
    if (deviceOfflineLabel) {
        deviceOfflineLabel->setVisible(true);
        deviceOfflineLabel->raise();
        qDebug() << "显示设备离线警告";
    }
}

// 隐藏设备离线警告
void HomePage::hideDeviceOfflineWarning()
{
    if (deviceOfflineLabel) {
        deviceOfflineLabel->setVisible(false);
        qDebug() << "隐藏设备离线警告";
    }
}

// 设备离线处理槽函数
void HomePage::onDeviceOffline()
{
    qDebug() << "检测到设备离线，显示警告";
    showDeviceOfflineWarning();

    // 通知所有界面设备已离线
    if (tempCurve) tempCurve->setConnectedState(false);
    if (myCar) myCar->setConnectedState(false);
    if (parkingSurveillance) parkingSurveillance->setConnectedState(false);
    if (setWig) setWig->setMqttConnected(false);
    if (search) search->setConnectedState(false);  // 添加这行
}

// 重写paintEvent函数绘制背景
void HomePage::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    if (!backgroundPixmap.isNull()) {
        // 使用平滑变换缩放图片以适应窗口大小
        QPixmap scaledPixmap = backgroundPixmap.scaled(this->size(),
                                                       Qt::IgnoreAspectRatio,
                                                       Qt::SmoothTransformation);
        painter.drawPixmap(0, 0, scaledPixmap);
    } else {
        // 如果图片加载失败，使用默认背景色
        painter.fillRect(this->rect(), QColor(240, 240, 240));
        painter.setPen(Qt::gray);
        painter.drawText(rect(), Qt::AlignCenter, "背景图片加载失败");
    }

    // 调用父类的paintEvent以确保其他控件正常绘制
    QWidget::paintEvent(event);
}

void HomePage::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);

    // 调整设备离线标签位置
    if (deviceOfflineLabel) {
        deviceOfflineLabel->setGeometry(this->width()/2 - 200, 50, 400, 80);
    }
}
void HomePage::onDataReceived(const QByteArray &msg)
{
    qDebug() << "[HomePage]: 接收到MQTT数据:" << QString(msg);

    QJsonDocument doc = QJsonDocument::fromJson(msg);
    if (!doc.isObject()) return;

    QJsonObject obj = doc.object();

    // 检查设备ID，确保是目标设备的消息
    if (obj.contains("id")) {
        QString deviceId = obj["id"].toString();
        if (deviceId != "dev01") {
            qDebug() << "[HomePage]: 忽略非目标设备消息";
            return;
        }
    }

    // 温湿度数据发送到温度曲线界面
    if (obj.contains("temp") || obj.contains("hum")) {
        if (tempCurve) {
            tempCurve->dataUpSlot(msg);
            qDebug() << "[HomePage]: 分发数据到温度曲线界面";
        }
    }

    // 汽车控制相关数据发送到My_Car界面
    if (obj.contains("led1_up") || obj.contains("led3_up") || obj.contains("key1_up") ||
            obj.contains("key2_up") || obj.contains("key3_up") || obj.contains("fan_up") ||
            obj.contains("motor_up") || obj.contains("air_up") || obj.contains("gd_jug_up")) {
        if (myCar) {
            myCar->dataUpSlot(msg);
            qDebug() << "[HomePage]: 分发数据到我的汽车界面";
        }
    }

    // 停车监控相关数据发送到Parking_Surveillance界面
    if (obj.contains("parking") || obj.contains("camera") || obj.contains("detection")) {
        if (parkingSurveillance) {
            parkingSurveillance->dataUpSlot(msg);
            qDebug() << "[HomePage]: 分发数据到停车监控界面";
        }
    }
}

void HomePage::sendStatusRequest()
{
    if (!GlobalVal::mqtt) {
        qDebug() << "MQTT客户端未初始化，无法发送状态请求";
        return;
    }

    QJsonObject statusRequest;
    statusRequest["cmd"] = "get_status";

    QJsonDocument doc(statusRequest);
    QByteArray message = doc.toJson();

    QMQTT::Message mqttMessage;
    mqttMessage.setTopic("MQTT  rec");
    mqttMessage.setPayload(message);

    GlobalVal::mqtt->publish(mqttMessage);
    qDebug() << "发送状态请求:" << QString(message);
}

// 新增：发送刷新请求
void HomePage::sendRefreshRequest()
{
    if (!GlobalVal::mqtt) {
        qDebug() << "MQTT客户端未初始化，无法发送刷新请求";
        return;
    }

    QJsonObject refreshRequest;
    refreshRequest["code"] = 3;  // 3表示刷新模式

    QJsonDocument doc(refreshRequest);
    QByteArray message = doc.toJson();

    QMQTT::Message mqttMessage;
    mqttMessage.setTopic("MQTT  rec");
    mqttMessage.setPayload(message);

    GlobalVal::mqtt->publish(mqttMessage);
    qDebug() << "发送刷新请求:" << QString(message);
}

// 新增：模式改变槽函数
void HomePage::onModeChanged(int mode)
{
    qDebug() << "[HomePage]: 模式已改变为:" << mode;
    // 刷新按钮已删除，此处不再需要处理刷新按钮的显示/隐藏
}

HomePage::~HomePage()
{
    delete ui;
    if (myCar) delete myCar;
    if (tempCurve) delete tempCurve;
    if (parkingSurveillance) delete parkingSurveillance;
    if (setWig) delete setWig;
    if (search) delete search;  // 释放Search界面内存
    if (deviceOfflineLabel) delete deviceOfflineLabel;
}

void HomePage::on_pushButton_clicked()
{
    QString ip = ui->line_mqtt_address->text();
    if (GlobalVal::mqtt) {
        GlobalVal::mqtt->setHost(QHostAddress(ip));
        GlobalVal::mqtt->setPort(1883);
        GlobalVal::mqtt->connectToHost();
    }
}

// 新增：发送模式请求
void HomePage::sendModeRequest(int mode)
{
    if (!GlobalVal::mqtt) {
        qDebug() << "MQTT客户端未初始化，无法发送模式请求";
        return;
    }

    QJsonObject modeRequest;
    modeRequest["code"] = mode;  // 1:循环, 2:对比, 3:刷新

    QJsonDocument doc(modeRequest);
    QByteArray message = doc.toJson();

    QMQTT::Message mqttMessage;
    mqttMessage.setTopic("MQTT  rec");
    mqttMessage.setPayload(message);

    GlobalVal::mqtt->publish(mqttMessage);
    qDebug() << "发送模式请求:" << QString(message) << "模式:" << mode;
}
